package com.ruoyi.web.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.web.controller.GuEveryDayController;
import com.ruoyi.web.domain.GuEveryDay;
import com.ruoyi.web.domain.GuGupiao;
import com.ruoyi.web.domain.GuNum;
import com.ruoyi.web.domain.vo.TengXunDataVo;
import com.ruoyi.web.domain.vo.TengXunGuVo;
import com.ruoyi.web.mapper.GuEveryDayMapper;
import com.ruoyi.web.mapper.GuGupiaoMapper;
import com.ruoyi.web.mapper.GuNumMapper;
import com.ruoyi.web.mapper.GuZtMapper;
import com.ruoyi.web.service.IGuEveryDayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;


/**
 * 每日行情Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-28
 */
@Service
public class GuEveryDayServiceImpl implements IGuEveryDayService
{
    @Autowired
    private GuEveryDayMapper guEveryDayMapper;
    private static final Logger log = LoggerFactory.getLogger(GuEveryDayServiceImpl.class);
    @Autowired
    private GuGupiaoMapper guGupiaoMapper;
    @Autowired
    private GuZtMapper guZtMapper;
    @Autowired
    private GuNumMapper guNumMapper;




    /**
     * 查询每日行情
     * 
     * @param id 每日行情主键
     * @return 每日行情
     */
    @Override
    public GuEveryDay selectGuEveryDayById(String id)
    {
        return guEveryDayMapper.selectGuEveryDayById(id);
    }

    /**
     * 查询每日行情列表
     * 
     * @param guEveryDay 每日行情
     * @return 每日行情
     */
    @Override
    public List<GuEveryDay> selectGuEveryDayList(GuEveryDay guEveryDay)
    {
        return guEveryDayMapper.selectGuEveryDayList(guEveryDay);
    }

    /**
     * 新增每日行情
     * 
     * @param guEveryDay 每日行情
     * @return 结果
     */
    @Override
    public int insertGuEveryDay(GuEveryDay guEveryDay)
    {
        return guEveryDayMapper.insertGuEveryDay(guEveryDay);
    }

    /**
     * 修改每日行情
     * 
     * @param guEveryDay 每日行情
     * @return 结果
     */
    @Override
    public int updateGuEveryDay(GuEveryDay guEveryDay)
    {
        return guEveryDayMapper.updateGuEveryDay(guEveryDay);
    }

    /**
     * 批量删除每日行情
     * 
     * @param ids 需要删除的每日行情主键
     * @return 结果
     */
    @Override
    public int deleteGuEveryDayByIds(String[] ids)
    {
        return guEveryDayMapper.deleteGuEveryDayByIds(ids);
    }

    /**
     * 删除每日行情信息
     * 
     * @param id 每日行情主键
     * @return 结果
     */
    @Override
    public int deleteGuEveryDayById(String id)
    {
        return guEveryDayMapper.deleteGuEveryDayById(id);
    }


    //从腾讯获取每天行情
    @Override
    public String getDataFromTengXun() {
        RestTemplate restTemplate = new RestTemplate();
        //设置Header
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        if(guEveryDayMapper.selectIsNullBuyData() > 1){
            return null;
        }
        headers.add("Content-Type", "application/json;charset=UTF-8");
        String url = "https://proxy.finance.qq.com/cgi/cgi-bin/rank/hs/getBoardRankList?_appver=11.17.0&board_code=aStock&sort_type=price&direct=down&offset=0&count=1";
        //发起请求,直接返回对象
        TengXunGuVo vo = restTemplate.getForObject(url, TengXunGuVo.class);
        if(vo.getData()!=null){
            int total = Integer.parseInt(vo.getData().getTotal());
            int i = total/100 ;
            int a = total % 100;
            if (a!=0){
                i++;
            }
            GuNum  guNum = guNumMapper.selectGuNumById(1);
            int num = guNum.getNum();
            for( int b =0 ;b< i;b++){
                String url1 = "https://proxy.finance.qq.com/cgi/cgi-bin/rank/hs/getBoardRankList?_appver=11.17.0&board_code=aStock&sort_type=price&direct=down&offset="+b*100+"&count=100";
                TengXunGuVo vo1 = restTemplate.getForObject(url1, TengXunGuVo.class);

                if(vo1.getData().getRank_list()!=null){
                    for(GuEveryDay guEveryDay : vo1.getData().getRank_list()){
                        //更新每天信息入库
                        guEveryDay.setId(UUID.randomUUID().toString().replace("-",""));
                        guEveryDay.setCreateTime(DateUtils.getNowDate());
                        guEveryDay.setGuNum(num);
                        guEveryDayMapper.insertGuEveryDay(guEveryDay);
                        GuGupiao guGupiao = new GuGupiao();
                        guGupiao.setId(UUID.randomUUID().toString().replace("-",""));
                        guGupiao.setCreateTime(DateUtils.getNowDate());
                        guGupiao.setGuCode(guEveryDay.getCode());
                        guGupiao.setGuName(guEveryDay.getName());
                        guGupiaoMapper.insertGuGupiao(guGupiao);
                        //如果涨跌停，就进入涨停表
                        if((guEveryDay.getCode().contains("sz00")||guEveryDay.getCode().contains("sh60"))&&guEveryDay.getZdf() != null ){
                            if( (Double.parseDouble(guEveryDay.getZdf())>=9 || Double.parseDouble(guEveryDay.getZdf())<=-9) && num > 1 ){
                                //查前一天的收盘价
                                String code = guEveryDay.getCode();
                                Integer guNums = guEveryDay.getGuNum();
                                GuEveryDay  guEveryDay1 = guEveryDayMapper.selectGuEveryDayByCodeAndNum(code,guNums);
                                double previousClose = Double.parseDouble(guEveryDay.getZxj()); // 前收盘价
                                double currentPrice = Double.parseDouble(guEveryDay1.getZxj());  // 当前价
                                double upLimit = 10.0;        // 涨停幅度（%）
                                double downLimit = 10.0;      // 跌停幅度（%）
                                double upPrice = previousClose * (1 + upLimit / 100);
                                double downPrice = previousClose * (1 - downLimit / 100);
                                if (Math.abs(currentPrice - upPrice) < 0.01) {
                                    guEveryDay.setIszd(1);
                                    if(guEveryDay1.getIszd() ==1){
                                        guEveryDay.setIsLian(1);
                                        if(guEveryDay1.getIsLian() == 1){
                                            guEveryDay.setLianNum(guEveryDay1.getLianNum()+1);
                                        }else {
                                            guEveryDay.setLianNum(1);
                                        }
                                    }
                                    guZtMapper.insertGuZt(guEveryDay);
                                } else if (Math.abs(currentPrice - downPrice) < 0.01) {
                                    guEveryDay.setIszd(0);
                                    guZtMapper.insertGuZt(guEveryDay);
                                }
                            }else{
                                if(Double.parseDouble(guEveryDay.getZdf())>9.7){
                                    guEveryDay.setIszd(1);
                                    guZtMapper.insertGuZt(guEveryDay);
                                } else if( Double.parseDouble(guEveryDay.getZdf())<-9.7){
                                    guEveryDay.setIszd(0);
                                    guZtMapper.insertGuZt(guEveryDay);
                                }
                            }
                        }
                    }
                }

            }
            guNum.setNum(++num);
            guNumMapper.updateGuNum(guNum);
        }
        log.info(vo.toString());
        return "";
    }


    /**
     * 依赖：tushare 的 trade_cal 接口（2000 积分）
     * 返回：yyyy-MM-dd 字符串
     */
    public static String prevTradeDate(String date) throws IOException {
        // 1. 调 trade_cal 接口，取 date 当天及之前 10 天的日历
        String url = "https://api.tushare.pro/api/public/v1/trade_cal" +
                "?exchange=SSE&start_date=" + date.replace("-","") +
                "&end_date=" + date.replace("-","");
       // String json = new String(new java.net.URL(url).openStream().readAllBytes());
        String json = new String();
        // 2. 解析 JSON，把 is_open=1 的日期倒序，第二个就是前一个交易日
        Pattern p = Pattern.compile("\"cal_date\":\"(\\d{8})\",\"is_open\":\"1\"");
        Matcher m = p.matcher(json);
        List<String> open = new ArrayList<>();
        while (m.find()) open.add(m.group(1));
        return open.size() < 2 ? null
                : open.get(1).substring(0,4) + "-" +
                open.get(1).substring(4,6) + "-" +
                open.get(1).substring(6,8);
    }


}
